from flask import Blueprint, jsonify, request
from db import db1
from utils.comm import get_data
import time

bp_users = Blueprint('yh', __name__)


@bp_users.route('/newsM')
def newsM():
    sql = """select * from news"""
    res = db1.find_all(sql)
    return jsonify({"code": 200, "list": res})


@bp_users.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == 'POST':
        data = get_data()
        print(data)
        sql = """select * from user where username = '%s'""" % data['username']
        res = db1.find_one(sql)
        if res:
            if res['password'] == data['password']:
                return jsonify({"code": 200, 'userid': res['id']})
            else:
                return jsonify({"code": 10010, 'mes': '密码错误'})
        else:
            return jsonify({"code": 10011, 'mes': '不存在此用户'})


@bp_users.route('/pls', methods=['POST', 'GET'])
def pls():
    if request.method == 'POST':
        data = get_data()
        print(data)
        sql = """insert into pl(content,userid,news_id) values('%s',%d,%d)""" % (
        data['pl'], int(data['userid']), int(data['id']))
        db1.insert(sql)
        return jsonify({"code": 200})


@bp_users.route('/xq')
def xq():
    id = request.args.get('id')
    sql = """select * from news where id = %d""" % int(id)
    res = db1.find_one(sql)
    timess = int(time.time())
    sql1 = """select * from news"""
    ress = db1.find_one(sql1)
    if ress['times']:
        nowtime = int(time.time())
        if nowtime - int(ress['times']) > 3600:
            sql3 = """update news set total_views = total_views+1"""
            db1.insert(sql3)
            sql4 = """update news set times = %d"""%nowtime
        else:
            return jsonify({"code":200})
    else:
        sql2 = """update news set times = %d where id = %d""" %(timess,id)
        db1.insert(sql2)
        sql4 = """update news set total_views = %d where id = %d""" %(1,id)
        db1.insert(sql4)
    return jsonify({"code": 200, "list": res})
